package com.atguigu.tingshu.common.login;

import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * @author atguigu-mqx
 * @ClassName TsLoginAspect
 * @description: TODO
 * @date 2025年02月22日
 * @version: 1.0
 */
@Aspect
@Component
@Slf4j
public class TsLoginAspect {

    @Autowired
    private RedisTemplate redisTemplate;

    //反射机制+aop的环绕通知，是否需要登录功能
    @Around("execution(* com.atguigu.tingshu.*.api.*.*(..)) && @annotation(tsLogin)")
    public Object tsLoginAspectAround(ProceedingJoinPoint point, TsLogin tsLogin) throws Throwable {
        Object object = new Object();
        //从请求头中获取 token;
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = attributes.getRequest();
        String token = request.getHeader("token");
        //  当需要登录时，用户未登录则抛出异常！ ResultCodeEnum.LOGIN_AUTH
        if (tsLogin.required()) {
            //  注解属性是需要登录，判断token是否为空
            if (StringUtils.isEmpty(token)) {
                throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
            }
            //从缓存中获取用户数据, 判断用户数据是否为空
            String userLoginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
            UserInfo userInfo = (UserInfo) redisTemplate.opsForValue().get(userLoginKey);
            //判断userInfo;
            if ( null == userInfo){
                throw new GuiguException(ResultCodeEnum.LOGIN_AUTH);
            }
        }
        try {
            //如果token不为空
            if (!StringUtils.isEmpty(token)){
                //获取缓存中的数据;
                String userLoginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;
                UserInfo userInfo = (UserInfo) redisTemplate.opsForValue().get(userLoginKey);
                //判断userInfo;
                if ( null != userInfo){
                    AuthContextHolder.setUserId(userInfo.getId());
                }
            }
            object = point.proceed();
            return object;
        } catch (Throwable e) {
            throw new RuntimeException(e);
        } finally {
            //调用remove() 方法防止内存泄漏
            AuthContextHolder.removeUserId();
        }
    }

}
